import logging

from auto_test.Config import Config
from utils.FilePath import FilePath


class Log:
    def __init__(
            self,
            name=Config.log['name'],
            formatter=Config.log['formatter'],
            level=Config.log['level'],
            fhPath=Config.log['fhPath']
    ):
        # 文件夹
        if not FilePath.fileExists(FilePath.getAbsPath(fhPath, isfile=False)):
            FilePath.makeDir(FilePath.getAbsPath(fhPath, isfile=False))

        # 老大logger
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)

        # 控制台小弟
        sh = logging.StreamHandler()
        sh.setLevel(level)
        sh.setFormatter(logging.Formatter(formatter))

        # 文件小弟
        fhList = []
        if type(fhPath) is list:
            for path in fhPath:
                fh = logging.FileHandler(path, mode='a', encoding='utf-8')
                fh.setLevel(level)
                fh.setFormatter(logging.Formatter(formatter))
                fh.close()
                fhList.append(fh)
        else:
            fh = logging.FileHandler(fhPath, mode='a', encoding='utf-8')
            fh.setLevel(level)
            fh.setFormatter(logging.Formatter(formatter))
            fh.close()
            fhList.append(fh)

        # 老大派小弟干活
        self.logger.addHandler(sh)
        for fh in fhList:
            self.logger.addHandler(fh)

    # 对外 返回老大
    def getLogger(self):
        return self.logger
